package com.itheima.mongo;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.mongoservice.FriendServiceApi;
import com.itheima.pojo.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendServiceApiImpl implements FriendServiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addFriends(Friend friend) {
        mongoTemplate.save(friend);
    }

    @Override
    public boolean isFriendExist(Long id, Long userId) {
        boolean exists = false;
        //自己和自己为好友不考虑
        if (!ObjectUtil.equal(id, userId)) {
            Query query = Query.query(Criteria.where("userId").is(id).and("friendId").is(userId));
            exists = mongoTemplate.exists(query, Friend.class);
        }
        return exists;
    }

    @Override
    public List<Friend> getFriends(Integer page, Integer pagesize, Long id) {
        Query query = Query.query(Criteria.where("userId").is(id))
                        .skip((page-1)*pagesize).limit(pagesize);
        return mongoTemplate.find(query, Friend.class);
    }

    @Override
    public List<Friend> findFriends(Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        return mongoTemplate.find(query, Friend.class);
    }

    //查询相互喜欢数目
    @Override
    public Integer getEachCount(Long uid) {
        Query query = new Query(Criteria.where("userId").is(uid));
        return mongoTemplate.find(query, Friend.class).size();
    }

    @Override
    public void deleteFriend(Long uid, Long id) {
        if (ObjectUtil.isNull(uid) || ObjectUtil.isNull(id)){
            return;
        }
        //删除双向好友
        Query query = Query.query(Criteria.where("userId").is(uid).and("friendId").is(id));
        mongoTemplate.remove(query, Friend.class);
        Query queryFriend = Query.query(Criteria.where("friendId").is(uid).and("userId").is(id));
        mongoTemplate.remove(queryFriend, Friend.class);
    }


}
